package com.ash.topic.consumer;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicSubscriber;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 消息的消费者（接受者）异步等待消息
 *
 * @author Ashin
 */
public class JMSConsumerAsyn {

    /**
     * 默认连接用户名
     */
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    /**
     * 默认连接密码
     */
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    /**
     * 默认连接地址
     */
    private static final String BROKE_URL = ActiveMQConnection.DEFAULT_BROKER_URL;

    public static void main(String[] args) throws Exception {
        String clientId = "test-durable-subscriber";
        // 实例化连接工厂
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKE_URL);

        // 通过连接工厂获取连接
        Connection connection = connectionFactory.createConnection();
        connection.setClientID(clientId);
        // 启动连接
        connection.start();
        // 创建session
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // 创建一个连接HelloWorld的消息队列
        Topic destination = session.createTopic("test-topic");

        TopicSubscriber messageConsumer = session.createDurableSubscriber(destination, clientId);

        messageConsumer.setMessageListener(new MessageListener() {

            @Override
            public void onMessage(Message message) {
                try {
                    TextMessage textMessage = (TextMessage) message;
                    // 取消息的内容
                    String text = textMessage.getText();
                    // 第八步：打印消息。
                    System.out.println("异步收到消息:" + text);
                } catch (JMSException e) {
                    e.printStackTrace();
                }

            }
        });

        // 等待键盘输入
        System.in.read();
        // 第九步：关闭资源
        messageConsumer.close();
        session.close();
        connection.close();

    }
}